const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
const { loadConfig } = require("../../src/utils/config");

const FFMPEG_V2_PATH = loadConfig().ffmpeg.path2 || "../bin/ffmpeg.exe";

/**
 * 创建3D翻页过渡效果
 * @param {string} image1 - 第一张图片路径
 * @param {string} image2 - 第二张图片路径
 * @param {string} output - 输出视频路径
 * @param {Object} options - 可选参数
 * @param {number} options.curlDuration - 翻页动画时长
 * @param {number} options.frame1Duration - 第一张图片展示时长
 * @param {number} options.frame2Duration - 第二张图片展示时长
 * @returns {Promise<string>} 输出文件路径
 */
function merge(image1 = "./image1.jpg", image2 = "./image2.jpg", output = "./page_flip_3d.mp4", options = {}) {
  return new Promise((resolve, reject) => {
    // 默认参数
    const { curlDuration = 2, frame1Duration = 3, frame2Duration = 4 } = options;

    // 检查输入文件是否存在
    if (!fs.existsSync(image1)) {
      reject(new Error(`找不到图片文件: ${image1}`));
      return;
    }

    if (!fs.existsSync(image2)) {
      reject(new Error(`找不到图片文件: ${image2}`));
      return;
    }

    // 检查GLSL着色器文件是否存在
    let shaderPath = path.join(__dirname, "./transitions/wind.glsl");
    if (!fs.existsSync(shaderPath)) {
      reject(new Error(`找不到GLSL着色器文件: ${shaderPath}`));
      return;
    }
    shaderPath = shaderPath.replace(/\\/g, "/");
    shaderPath = shaderPath.replace(":", "\\\\:");

    console.log(`  GLSL着色器文件路径: ${shaderPath}`);
    // 构建FFmpeg命令参数
    const args = [
      "-loop",
      "1",
      "-i",
      image1.replace(/\\/g, "/"),
      "-loop",
      "1",
      "-i",
      image2.replace(/\\/g, "/"),
      "-filter_complex",
      `[0:v]trim=duration=${frame1Duration},setpts=PTS-STARTPTS[v0];` +
      `[1:v]trim=duration=${frame2Duration},setpts=PTS-STARTPTS+${frame1Duration}/TB[v1];` +
      `[v0][v1]gltransition=source=${shaderPath}:duration=${curlDuration}:offset=${frame1Duration}`,
      "-y",
      `${output}`,
    ];

    console.log("  正在创建3D翻页过渡效果...");
    console.log("  执行命令:", FFMPEG_V2_PATH, args.join(" "));

    // 执行FFmpeg命令
    const ffmpeg = spawn(FFMPEG_V2_PATH, args);

    ffmpeg.stdout.on("data", data => {
      //console.log(`stdout: ${data}`);
    });

    ffmpeg.stderr.on("data", data => {
      //console.error(`stderr: ${data}`);
    });

    ffmpeg.on("close", code => {
      if (code === 0) {
        console.log(`  处理完成！输出文件: ${output}`);
        resolve(output);
      } else {
        reject(new Error(`FFmpeg进程退出，退出码: ${code}`));
      }
    });

    ffmpeg.on("error", error => {
      reject(new Error(`启动FFmpeg时出错: ${error.message}`));
    });
  });
}

module.exports = {
  merge,
};
